/**************************************************************
  > File Name: sendShmget.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年02月23日 星期三 03时16分19秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/wait.h>

#define PATHNAME "log"
#define TIDSIZE 3

sem_t *semp;
int *shmp = NULL;

void *pthread_handler(void *args)
{
	int n = 100000LL;		
	sem_wait(semp);
	while (n--)
	{
		(*shmp)++;
	}
	sem_post(semp);

	pthread_exit(NULL);
}

int main(int argc, char **argv)
{
	key_t key;
	int shmid;
	int proc_id = 1;
	size_t size = 4096;
	pthread_t tid[TIDSIZE];

	key = ftok(PATHNAME, proc_id);
	if (key < 0)
	{
		perror("ftok()");
		exit(1);
	}
	
	shmid = shmget(key, size, IPC_CREAT | 0666);
	if (shmid < 0)
	{
		perror("shmget()");
		exit(1);
	}
	
	shmp = shmat(shmid, NULL, 0);
	if (shmp == NULL)
	{
		perror("shmat()");
		exit(1);
	}
	
	*shmp = 0;

	semp = (sem_t *)malloc(sizeof(sem_t));
	
	if (sem_init(semp, 0, 1) < 0)
	{
		perror("sem_init()");
		exit(1);
	}
	
	for (int i = 0; i < 3; i++)
	{
		pthread_create(tid+i, NULL, pthread_handler, NULL);
	}
	
	for (int i = 0; i < 3; i++)
	{
		pthread_join(tid[i], NULL);	
	}

	printf("%d\n",*shmp);
	
	sem_destroy(semp);
	shmdt(shmp);
    exit(0);
}
